/*
 * clock.c
 *
 *  Created on: 2018-3-13
 *      Author: Iron
 */
#include <time.h>
#include "sys/clock.h"
#include "sys/etimer.h"
#include "user_interface.h"
#include "osapi.h"

/*----------------------------------------------------------------------------*/
static volatile clock_time_t clock_ticks;
extern volatile uint32_t rtimer_clock;

/*----------------------------------------------------------------------------*/
void contiki_main_clock_isr_cb(clock_time_t ticks);

/*----------------------------------------------------------------------------*/
#define CONTIKI_CLOCK_TIMER_INTERVAL  (1000 / CLOCK_CONF_SECOND) 	/* milliseconds */
LOCAL os_timer_t conitki_clock_timer;

LOCAL void ICACHE_FLASH_ATTR conitki_clock_timer_cb(void *arg)
{
    clock_ticks++; 			// contiki system clock
    rtimer_clock++;			// rtimer

	if(etimer_pending()) {
		etimer_request_poll();
	}

	contiki_main_clock_isr_cb(clock_ticks);
}

void clock_init(void)
{
	os_timer_disarm(&conitki_clock_timer);
	os_timer_setfn(&conitki_clock_timer, (os_timer_func_t *)conitki_clock_timer_cb, (void *)0);
	os_timer_arm(&conitki_clock_timer, CONTIKI_CLOCK_TIMER_INTERVAL, 1);
}

/*----------------------------------------------------------------------------*/
CCIF clock_time_t clock_time(void)
{
	return clock_ticks;
}

CCIF unsigned long clock_seconds(void)
{
	os_printf("conitki get clock_seconds\n");
	return time(NULL);
}
